package vip.xiaonuo.smzq.modular.hisi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.smzq.core.tools.excel.ExcelToReadUtil;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.core.utils.UserUtil;
import vip.xiaonuo.smzq.modular.deom.ToolData;
import vip.xiaonuo.smzq.modular.deom.TypeProcessing;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb01Zh;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb06Kc;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb01ZhMapper;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb06KcMapper;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb08XzqhMapper;
import vip.xiaonuo.smzq.modular.hisi.entity.KsZyclhz;
import vip.xiaonuo.smzq.modular.hisi.entity.Kshz;
import vip.xiaonuo.smzq.modular.hisi.entity.constants.ChartTypeConstants;
import vip.xiaonuo.smzq.modular.hisi.entity.vo.*;
import vip.xiaonuo.smzq.modular.hisi.mapper.KsZyclhzMapper;
import vip.xiaonuo.smzq.modular.hisi.mapper.KshzMapper;
import vip.xiaonuo.smzq.modular.hisi.service.IKshzService;
import vip.xiaonuo.smzq.modular.kcl.entity.Ks;
import vip.xiaonuo.smzq.modular.kcl.mapper.KsMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.KslsjuMapper;
import vip.xiaonuo.smzq.modular.user.entity.User;
import vip.xiaonuo.smzq.modular.user.mapper.UserMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 矿山信息汇总 服务实现类
 *
 * @author sqq
 * @since 2024-07-04
 */
@Service
public class KshzServiceImpl extends ServiceImpl<KshzMapper, Kshz> implements IKshzService {

    @Resource
    private KshzMapper kshzMapper;
    @Resource
    private KsMapper ksMapper;
    @Resource
    private Cb08XzqhMapper cb08XzqhMapper;//行政区划
    @Resource
    private Cb06KcMapper cb06KcMapper;//矿产
    @Resource
    private Cb01ZhMapper cb01ZhMapper;//字典综合
    @Resource
    private UserMapper userMapper;//用户
    @Resource
    private KsZyclhzMapper ksZyclhzMapper;//矿山资源储量数据
    @Resource
    private KslsjuMapper kslsjuMapper; //矿山历史

    @Override
    public Page<Kshz> page(Kshz kshz) {
        QueryWrapper<Kshz> queryWrapper = new QueryWrapper<>();
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }


    /**
     * 查询统计-矿山信息查询
     */
    @Override
    public Page<KsxxhzVo> queryKshzPage(CxtjMhtj cxtjMhtj, MultipartFile file) {
        List<ExcelDataVo> excelDataVoList = new ArrayList<>();
        try {
            if (file != null) {
                excelDataVoList = ExcelToReadUtil.excelRearer(file.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());


        Page<Kshz> page = new Page<>();
        Page<KsxxhzVo> returnPage = new Page<>();

        page.setCurrent(cxtjMhtj.getCurrent());
        page.setSize(cxtjMhtj.getSize());

        LambdaQueryWrapper<Kshz> queryWrapper = new LambdaQueryWrapper<>();
        // 拼接年度信息
        if (cxtjMhtj.getNd() != null) {
            queryWrapper.eq(Kshz::getNd, cxtjMhtj.getNd());
        }

// 拼接矿山名称信息
        if (cxtjMhtj.getKsmc() != null) {
            queryWrapper.like(Kshz::getKsmc, cxtjMhtj.getKsmc());
        }

// 拼接矿山编号信息
        if (cxtjMhtj.getKsbh() != null) {
            queryWrapper.like(Kshz::getKsbh, cxtjMhtj.getKsbh());
        }

// 拼接矿区编号信息
        if (cxtjMhtj.getKqbh() != null) {
            queryWrapper.like(Kshz::getKqbh, cxtjMhtj.getKqbh());
        }

// 拼接矿区名称
        if (cxtjMhtj.getKqmc() != null) {
            queryWrapper.like(Kshz::getKqmc, cxtjMhtj.getKqmc());
        }

// 拼接矿种
        if (cxtjMhtj.getKzbh() != null) {
            if (cxtjMhtj.getKzbh().contains(",") || !cxtjMhtj.getKzbh().contains("_")) {
                List<Integer> kzbhList = TypeProcessing.strToListComma(cxtjMhtj.getKzbh());
                queryWrapper.in(Kshz::getKcdm, kzbhList);
                //queryWrapper.eq("kqlx", 2);

            } else {
                List<Integer> kzbhList = TypeProcessing.strToList(cxtjMhtj.getKzbh());
                if (kzbhList != null && kzbhList.size() == 3) {
                    if (kzbhList.get(0) == 2) {
                        queryWrapper.eq(Kshz::getKcdm, kzbhList.get(1));
                    } else if (kzbhList.get(0) == 3) {
                        queryWrapper.eq(Kshz::getKcdm, kzbhList.get(1));
                        queryWrapper.eq(Kshz::getTjdx, kzbhList.get(2));
                    }
                }
            }
        }
// 登记分类编号
        if (cxtjMhtj.getDjflbh() != null) {
            queryWrapper.eq(Kshz::getDjflbh, cxtjMhtj.getDjflbh());
        }

// 矿业权人
        if (cxtjMhtj.getKyqr() != null) {
            queryWrapper.eq(Kshz::getKyqr, cxtjMhtj.getKyqr());
        }

// 规模
        if (cxtjMhtj.getGm() != null) {
            queryWrapper.eq(Kshz::getGm, cxtjMhtj.getGm());
        }

// 利用情况
        if (cxtjMhtj.getSfly() != null) {
            queryWrapper.eq(Kshz::getSfly, cxtjMhtj.getSfly());
        }

// 有效期模糊查询
        if (cxtjMhtj.getYxq() != null) {
            queryWrapper.like(Kshz::getJzyxq, cxtjMhtj.getYxq());
        }

// 上表标识 支持多选（1,2,3）
        if (cxtjMhtj.getSbbs() != null) {
            List<Integer> sbbsList = Arrays.stream(cxtjMhtj.getSbbs().split(","))
                    .map(String::trim)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            queryWrapper.in(Kshz::getSbbsm, sbbsList);
        }

// 矿山规模
        if (cxtjMhtj.getKsgmm() != null) {
            queryWrapper.eq(Kshz::getKsgmm, cxtjMhtj.getKsgmm());
        }

// 生产状态
        if (cxtjMhtj.getScztm() != null) {
            queryWrapper.eq(Kshz::getScztm, cxtjMhtj.getScztm());
        }

// 行政区代码级联多选
        if (cxtjMhtj.getXzqh() != null) {
            List<String> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());
            queryWrapper.in(Kshz::getXzqdm, xzqhList);
        } else {
            String xzqh = user.getOrgId() != null ? user.getOrgId() : "130000";
            xzqh = xzqh.replaceAll("0+$", "");
            queryWrapper.like(Kshz::getXzqdm, xzqh);
        }

// 许可证号
        if (cxtjMhtj.getXkzh() != null) {
            queryWrapper.eq(Kshz::getXkzh, cxtjMhtj.getXkzh());
        }

// 勘察程度
        if (cxtjMhtj.getKccd() != null) {
            queryWrapper.eq(Kshz::getKcjdm, cxtjMhtj.getKccd());
        }

// 开采情况（0未开采，1开采）
        if (cxtjMhtj.getKcqk() != null) {
            queryWrapper.eq(Kshz::getKcqk, cxtjMhtj.getKcqk());
        }

// 是否出界（0未出界，1出界）
        if (cxtjMhtj.getSfcj() != null) {
            queryWrapper.eq(Kshz::getSfcj, cxtjMhtj.getSfcj());
        }

// 矿产组合码
        if (cxtjMhtj.getKczh() != null) {
            LambdaQueryWrapper<Cb01Zh> queryWrapperCb01 = new LambdaQueryWrapper<>();
            queryWrapperCb01.eq(Cb01Zh::getBh, 16);
            queryWrapperCb01.eq(Cb01Zh::getBnm, Integer.valueOf(cxtjMhtj.getKczh()));
            Cb01Zh cb01Zh = cb01ZhMapper.selectOne(queryWrapperCb01);
            if (cb01Zh != null) {
                queryWrapper.eq(Kshz::getKczhm, cb01Zh.getBh());
            }
        }

// 矿业权类型（1：无矿权，2：采矿权，3：探矿权）
        if (cxtjMhtj.getKqlx() != null) {
            queryWrapper.eq(Kshz::getKqlx, cxtjMhtj.getKqlx());
        }

//excel上传时许可证号条件
        if (excelDataVoList.size() > 0) {
            List<String> xkzhList = new ArrayList<>();
            for (ExcelDataVo excelDataVo : excelDataVoList) {
                xkzhList.add(excelDataVo.getXkzh());
            }
            queryWrapper.in(Kshz::getXkzh, xkzhList);
        }

// 排序
        queryWrapper.orderByDesc(Kshz::getNd);
        queryWrapper.orderByAsc(Kshz::getKqbh);

        page = kshzMapper.selectPage(page, queryWrapper);
        List<Kshz> kshzList = page.getRecords();

        List<KsxxhzVo> ksxxhzVoList = new ArrayList<>();

        for (Kshz kshz : kshzList) {
            KsxxhzVo ksxxhzVo = new KsxxhzVo();
            BeanUtil.copyProperties(kshz, ksxxhzVo);

            String xzqhmc = cb08XzqhMapper.getXzqhmc(Integer.parseInt(kshz.getXzqdm()));
            ksxxhzVo.setXzqhmc(xzqhmc);
            countKszy(kshz, ksxxhzVo, true);


            LambdaQueryWrapper<Cb06Kc> queryWrapperKc = new LambdaQueryWrapper<>();
            queryWrapperKc.eq(Cb06Kc::getKcdm, ksxxhzVo.getKcdm());
            queryWrapperKc.last("limit 1");
            Cb06Kc cb06Kc = cb06KcMapper.selectOne(queryWrapperKc);
            ksxxhzVo.setKcmc(cb06Kc.getKcmc());
            ksxxhzVo.setJsdxmc(cb06Kc.getJsdxmc());
            ksxxhzVoList.add(ksxxhzVo);
        }

        returnPage.setSize(page.getSize());
        returnPage.setCurrent(page.getCurrent());
        returnPage.setTotal(page.getTotal());
        returnPage.setRecords(ksxxhzVoList);
        return returnPage;
    }

    /**
     * 查询统计-矿山信息查询总计
     */
    @Override
    public KsxxcxhjVo queryKshzCount(CxtjMhtj cxtjMhtj, MultipartFile file) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());


        KsxxcxhjVo ksxxcxhjVo = new KsxxcxhjVo();

        if (cxtjMhtj.getKzbh() == null) {
            return ksxxcxhjVo;
        }

        // excel上传时许可证号条件
        List<ExcelDataVo> excelDataVoList = new ArrayList<>();
        try {
            if (file != null) {
                excelDataVoList = ExcelToReadUtil.excelRearer(file.getInputStream());

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //通过此方法去查询矿权并计算资源储量
        MPJLambdaWrapper<Kshz> queryWrapper = new MPJLambdaWrapper<>(Kshz.class);

        queryWrapper.selectAs(Kshz::getKqbh, KsQueryCriteria::getKqbh)
                .selectAs(Kshz::getKcdm, KsQueryCriteria::getKcdm)
                .selectAs(Kshz::getNd, KsQueryCriteria::getNd)
                .selectAs(Kshz::getTjdx, KsQueryCriteria::getTjdx);
        // 统一处理简单字段
        processSimpleCondition(queryWrapper, cxtjMhtj);

        // 处理复杂字段
        processComplexCondition(queryWrapper, cxtjMhtj, user, excelDataVoList);

        //分组排序
        queryWrapper.groupBy(Kshz::getKqbh, Kshz::getKcdm, Kshz::getNd, Kshz::getTjdx);
        queryWrapper.orderByDesc(Kshz::getKqbh);

        List<KsQueryCriteria> ksList = this.getBaseMapper().selectJoinList(KsQueryCriteria.class, queryWrapper);

        if (ksList != null && ksList.size() > 0) {
            ksxxcxhjVo = getZyzlzj(ksList);
        }

        List<ExcelDataVo> finalExcelDataVoList = excelDataVoList;

        // 子查询
        MPJLambdaWrapper<Kshz> subQuery = new MPJLambdaWrapper<>(Kshz.class);
        subQuery.select(Kshz::getKqbh, Kshz::getKcdm, Kshz::getNd, Kshz::getTjdx, Kshz::getDjflbh);
        processSimpleCondition(subQuery, cxtjMhtj);
        processComplexCondition(subQuery, cxtjMhtj, user, finalExcelDataVoList);
        subQuery.groupBy(Kshz::getKqbh, Kshz::getKcdm, Kshz::getNd, Kshz::getTjdx, Kshz::getDjflbh);

        List<Map<String, Object>> maps = this.getBaseMapper().selectJoinMaps(subQuery);

        long zj = maps.size();

        ksxxcxhjVo.setZj((int) zj);

        return ksxxcxhjVo;
    }


    /**
     * 辅助方法：处理简单字段
     *
     * @param queryWrapper
     * @param cxtjMhtj
     */
    public void processSimpleCondition(MPJLambdaWrapper<Kshz> queryWrapper, CxtjMhtj cxtjMhtj) {
        // 动态拼接查询条件，直接将 if 判断写入 eq 方法中
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getNd()), Kshz::getNd, cxtjMhtj.getNd()); // 年度
        queryWrapper.like(ObjectUtil.isNotEmpty(cxtjMhtj.getKsmc()), Kshz::getKsmc, cxtjMhtj.getKsmc()); // 矿山名称
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getKsbh()), Kshz::getKsbh, cxtjMhtj.getKsbh()); // 矿山编号
        queryWrapper.like(ObjectUtil.isNotEmpty(cxtjMhtj.getKqbh()), Kshz::getKqbh, cxtjMhtj.getKqbh()); // 矿区编号
        queryWrapper.like(ObjectUtil.isNotEmpty(cxtjMhtj.getKqmc()), Kshz::getKqmc, cxtjMhtj.getKqmc()); // 矿区名称
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getDjflbh()), Kshz::getDjflbh, cxtjMhtj.getDjflbh()); // 登记分类编号
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getKyqr()), Kshz::getKyqr, cxtjMhtj.getKyqr()); // 矿业权人
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getGm()), Kshz::getGm, cxtjMhtj.getGm()); // 规模
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getSfly()), Kshz::getSfly, cxtjMhtj.getSfly()); // 利用情况
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getYxq()), Kshz::getJzyxq, cxtjMhtj.getYxq()); // 有效期模糊查询
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getKsgmm()), Kshz::getKsgmm, cxtjMhtj.getKsgmm());//矿山规模
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getScztm()), Kshz::getScztm, cxtjMhtj.getScztm()); //生产状态
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getXkzh()), Kshz::getXkzh, cxtjMhtj.getXkzh()); // 许可证号
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getKccd()), Kshz::getKcjdm, cxtjMhtj.getKccd()); // 勘察程度
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getKcqk()), Kshz::getKcqk, cxtjMhtj.getKcqk()); // 开采情况
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getSfcj()), Kshz::getSfcj, cxtjMhtj.getSfcj()); // 是否出界
        queryWrapper.eq(ObjectUtil.isNotEmpty(cxtjMhtj.getKqlx()), Kshz::getKqlx, cxtjMhtj.getKqlx()); // 矿业权类型
    }


    /**
     * 辅助方法：处理复杂字段
     *
     * @param queryWrapper
     * @param cxtjMhtj
     * @param user
     * @param excelDataVoList
     */
    private void processComplexCondition(MPJLambdaWrapper<Kshz> queryWrapper, CxtjMhtj cxtjMhtj, User user, List<ExcelDataVo> excelDataVoList) {
        // 矿种（复杂逻辑）
        if (ObjectUtil.isNotEmpty(cxtjMhtj.getKzbh())) {
            handleKzbhCondition(queryWrapper, cxtjMhtj.getKzbh());
        }

        // 上表标识（多选）
        if (ObjectUtil.isNotEmpty(cxtjMhtj.getSbbs())) {
            List<Integer> sbbsList = Arrays.stream(cxtjMhtj.getSbbs().split(","))
                    .map(String::trim)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            queryWrapper.in(Kshz::getSbbsm, sbbsList);
        }

        // 行政区代码级联多选
        if (ObjectUtil.isNotEmpty(cxtjMhtj.getXzqh())) {
            List<String> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());
            queryWrapper.in(Kshz::getXzqdm, xzqhList);
        } else {
            String xzqh = user.getOrgId() != null ? user.getOrgId() : "130000";
            xzqh = xzqh.replaceAll("0+$", "");
            queryWrapper.like(Kshz::getXzqdm, xzqh);
        }

        // 矿产组合码
        if (ObjectUtil.isNotEmpty(cxtjMhtj.getKczh())) {
            LambdaQueryWrapper<Cb01Zh> queryWrapperCb01 = new LambdaQueryWrapper<>();
            queryWrapperCb01.eq(Cb01Zh::getBh, 16);
            queryWrapperCb01.eq(Cb01Zh::getBnm, Integer.valueOf(cxtjMhtj.getKczh()));
            Cb01Zh cb01Zh = cb01ZhMapper.selectOne(queryWrapperCb01);
            if (cb01Zh != null) {
//                queryWrapper.eq(Kshz::getKczhm, cb01Zh.getBnm()).or().eq(Kshz::getKczhm, cb01Zh.getDm());
                queryWrapper .and(wrapper -> wrapper
                        .eq(Kshz::getKczhm, cb01Zh.getBnm())
                        .or()
                        .eq(Kshz::getKczhm, cb01Zh.getDm())
                );


            }
        }

        // Excel上传时许可证号条件
        if (excelDataVoList!=null&&excelDataVoList.size()>0) {
            List<String> xkzhList = excelDataVoList.stream()
                    .map(ExcelDataVo::getXkzh)
                    .collect(Collectors.toList());
            queryWrapper.in(Kshz::getXkzh, xkzhList);
        }
    }


    /**
     * 矿种处理逻辑提取
     *
     * @param queryWrapper
     * @param kzbh
     */
    private void handleKzbhCondition(MPJLambdaWrapper<Kshz> queryWrapper, String kzbh) {
        if (kzbh.contains(",") || !kzbh.contains("_")) {
            List<Integer> kzbhList = TypeProcessing.strToListComma(kzbh);
            queryWrapper.in(Kshz::getKcdm, kzbhList);
        } else {
            List<Integer> kzbhList = TypeProcessing.strToList(kzbh);
            if (kzbhList != null && kzbhList.size() == 3) {
                switch (kzbhList.get(0)) {
                    case 2:
                        queryWrapper.eq(Kshz::getKcdm, kzbhList.get(1));
                        break;
                    case 3:
                        queryWrapper.eq(Kshz::getKcdm, kzbhList.get(1));
                        queryWrapper.eq(Kshz::getTjdx, kzbhList.get(2));
                        break;
                    default:
                        break;
                }
            }
        }
    }


    /**
     * 查询统计-矿产地信息查询
     */
    @Override
    public Page<KsxxhzVo> queryKcdxxhzPage(CxtjMhtj cxtjMhtj) {
        cxtjMhtj.setDjflbh(null);
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        long current = cxtjMhtj.getCurrent();
        long size = cxtjMhtj.getSize();

        Page<KsxxhzVo> page = new Page<>(current, size);

        if (current < 1) {
            return page;
        }

        MPJLambdaWrapper<Kshz> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAs(Kshz::getNd, KsxxhzVo::getNd) // 统计年度
                .selectMax(Kshz::getXzqdm, KsxxhzVo::getXzqdm) // 行政区代码
                .selectMax(Kshz::getKqmc, KsxxhzVo::getKqmc) // 矿区名称
                .selectAs(Kshz::getKqbh, KsxxhzVo::getKqbh) // 矿区编号
                .selectAs(Kshz::getKcmc, KsxxhzVo::getKcmc) // 矿产名称
                .selectAs(Kshz::getJsdxmc, KsxxhzVo::getJsdxmc) // 统计对象名称
                .selectMax(Kshz::getKcjdm, KsxxhzVo::getKcjdm) //勘察阶段码
                .selectMax(Kshz::getGm, KsxxhzVo::getGm) // 规模
                .selectMax(Kshz::getSfly, KsxxhzVo::getSfly) // 是否利用
                .selectMax(Kshz::getKczh, KsxxhzVo::getKczh) // 矿种组合码
                .selectMax(Kshz::getKcjdmc, KsxxhzVo::getKcjdmc)  // 勘察阶段名称
                .selectMax(KsZyclhz::getJsldw, KsxxhzVo::getJsldw) // 金属量单位
                .selectAs("CAST(sum(ncbyjsl) AS DECIMAL(18,2))", KsxxhzVo::getNcbyjsl)
                .selectAs("CAST(sum(ncljjsl) AS DECIMAL(18,2))", KsxxhzVo::getNcljjsl)
                .selectAs("CAST(sum(kcljsl) AS DECIMAL(18,2))", KsxxhzVo::getKcljsl)
                .selectAs("CAST(sum(ssljsl) AS DECIMAL(18,2))", KsxxhzVo::getSsljsl)
                .selectAs("CAST(sum(kczjjsl) AS DECIMAL(18,2))", KsxxhzVo::getKczjjsl)
                .selectAs("CAST(sum(cszjjsl) AS DECIMAL(18,2))", KsxxhzVo::getCszjjsl)
                .selectAs("CAST(sum(spyfjsl) AS DECIMAL(18,2))", KsxxhzVo::getSpyfjsl)
                .selectAs("CAST(sum(otherdatajsl) AS DECIMAL(18,2))", KsxxhzVo::getOtherdatajsl)
                .selectAs("CAST(sum(nmbyjsl) AS DECIMAL(18,2))", KsxxhzVo::getNmbyjsl)
                .selectAs("CAST(sum(ljcmjsl) AS DECIMAL(18,2))", KsxxhzVo::getLjcmjsl)
                .selectMax(KsZyclhz::getJsldw, KsxxhzVo::getJsldw) // 矿石量单位
                .selectAs("CAST(sum(ncbyksl) AS DECIMAL(18,2))", KsxxhzVo::getNcbyksl)
                .selectAs("CAST(sum(ncljksl) AS DECIMAL(18,2))", KsxxhzVo::getNcljksl)
                .selectAs("CAST(sum(kclksl) AS DECIMAL(18,2))", KsxxhzVo::getKclksl)
                .selectAs("CAST(sum(sslksl) AS DECIMAL(18,2))", KsxxhzVo::getSslksl)
                .selectAs("CAST(sum(kczjksl) AS DECIMAL(18,2))", KsxxhzVo::getKczjksl)
                .selectAs("CAST(sum(cszjksl) AS DECIMAL(18,2))", KsxxhzVo::getCszjksl)
                .selectAs("CAST(sum(spyfksl) AS DECIMAL(18,2))", KsxxhzVo::getSpyfksl)
                .selectAs("CAST(sum(otherdataksl) AS DECIMAL(18,2))", KsxxhzVo::getOtherdataksl)
                .selectAs("CAST(sum(nmbyksl) AS DECIMAL(18,2))", KsxxhzVo::getNmbyksl)
                .selectAs("CAST(sum(ljcmksl) AS DECIMAL(18,2))", KsxxhzVo::getLjcmksl);
        queryWrapper.leftJoin(KsZyclhz.class, on -> on
                .eq(KsZyclhz::getNd, Kshz::getNd)
                .eq(KsZyclhz::getKqbh, Kshz::getKqbh)
                .eq(KsZyclhz::getDjflbh, Kshz::getDjflbh)
                .eq(KsZyclhz::getKcdm, Kshz::getKcdm)
                .eq(KsZyclhz::getTjdx, Kshz::getTjdx)
        );
        queryWrapper.ne(Kshz::getSbbs, "3");
        queryWrapper.in(KsZyclhz::getZycllx, "TM", "KZ", "TD");

                // 统一处理简单字段
        processSimpleCondition(queryWrapper, cxtjMhtj);

        // 处理复杂字段
        processComplexCondition(queryWrapper, cxtjMhtj, user, null);
        queryWrapper.groupBy(Kshz::getKqbh, Kshz::getKcmc, Kshz::getJsdxmc,Kshz::getNd);
        queryWrapper.orderByAsc(Kshz::getKqbh);

        //查询总数
        page  = kshzMapper.selectJoinPage(page,KsxxhzVo.class, queryWrapper);

        //查询分页
      List<KsxxhzVo>  ksxxhzVoList = page.getRecords();

        for (KsxxhzVo ksQueryCriteria : ksxxhzVoList) {
            String xzqhmc = cb08XzqhMapper.getXzqhmc(Integer.parseInt(ksQueryCriteria.getXzqdm()));
            ksQueryCriteria.setXzqhmc(xzqhmc);
        }

        page.setRecords(ksxxhzVoList);

        return page;
    }

    /**
     * 矿产地信息查询总计
     *
     * @param cxtjMhtj
     * @return
     */
    @Override
    public KsxxcxhjVo queryKcdxxCount(CxtjMhtj cxtjMhtj) {
        cxtjMhtj.setDjflbh(null);

        KsxxcxhjVo ksxxcxhjVo = new KsxxcxhjVo();
        if (cxtjMhtj.getKzbh() == null) {
            return ksxxcxhjVo;
        }
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());


        //通过此方法去查询矿权并计算资源储量
        MPJLambdaWrapper<Kshz> queryWrapper = new MPJLambdaWrapper<>(Kshz.class);

        queryWrapper.selectAs(Kshz::getKqbh, KsQueryCriteria::getKqbh)
                .selectAs(Kshz::getKcdm, KsQueryCriteria::getKcdm)
                .selectAs(Kshz::getNd, KsQueryCriteria::getNd)
                .selectAs(Kshz::getTjdx, KsQueryCriteria::getTjdx);
        // 统一处理简单字段
        processSimpleCondition(queryWrapper, cxtjMhtj);

        // 处理复杂字段
        processComplexCondition(queryWrapper, cxtjMhtj, user, null);

        //分组排序
        queryWrapper.groupBy(Kshz::getKqbh, Kshz::getKcdm, Kshz::getNd, Kshz::getTjdx);
        queryWrapper.orderByDesc(Kshz::getKqbh);

        List<KsQueryCriteria> ksList = this.getBaseMapper().selectJoinList(KsQueryCriteria.class, queryWrapper);


        if (ksList != null && ksList.size() > 0) {
            ksxxcxhjVo = getZyzlzj(ksList);
        }

        // 子查询
        MPJLambdaWrapper<Kshz> subQuery = new MPJLambdaWrapper<>(Kshz.class);
        subQuery.select(Kshz::getKqbh, Kshz::getKcdm, Kshz::getNd, Kshz::getTjdx, Kshz::getKczhm, Kshz::getGm, Kshz::getKcjdm,Kshz::getKcqk, Kshz::getSfly);
        processSimpleCondition(subQuery, cxtjMhtj);
        processComplexCondition(subQuery, cxtjMhtj, user, null);
        subQuery.groupBy(Kshz::getKqbh, Kshz::getKcdm, Kshz::getNd, Kshz::getTjdx, Kshz::getKczhm, Kshz::getGm, Kshz::getKcjdm,Kshz::getKcqk, Kshz::getSfly);

        List<Map<String, Object>> maps = this.getBaseMapper().selectJoinMaps(subQuery);

        long zj = maps.size();

        ksxxcxhjVo.setZj((int) zj);

        return ksxxcxhjVo;

    }


    /**
     * 计算矿山资源量
     */
    public void countKszy(Kshz kshz, KsxxhzVo ksxxhzVo, boolean isKs) {

        //查询年度下所有的资源储量没有则全部数据
        List<KsZyclhz> ksZyclhzList = new ArrayList<>();
        LambdaQueryWrapper<KsZyclhz> ksZyclhzQueryWrapper = new LambdaQueryWrapper<>();
        ksZyclhzQueryWrapper.eq(KsZyclhz::getNd, kshz.getNd());
        ksZyclhzQueryWrapper.eq(KsZyclhz::getKqbh, kshz.getKqbh());
        ksZyclhzQueryWrapper.eq(KsZyclhz::getKcdm, kshz.getKcdm());
        if (isKs) {
            ksZyclhzQueryWrapper.eq(KsZyclhz::getDjflbh, kshz.getDjflbh());
            ksZyclhzQueryWrapper.eq(KsZyclhz::getTjdx, kshz.getTjdx());
        }
        ksZyclhzQueryWrapper.in(KsZyclhz::getZycllx, "TM", "TD", "KZ");
        ksZyclhzList = ksZyclhzMapper.selectList(ksZyclhzQueryWrapper);


        if (ksZyclhzList.size() > 0) {

            KsZyclhz zycl = ksZyclhzList.get(0);

            //年初保有金属量
            double ncbyJsl = 0.0;
            //年初累计金属量
            double ncljJsl = 0.0;
            //开采量 金属量
            double kclJsl = 0;
            //损失量 金属量
            double sslJsl = 0;
            //勘察增减（±） 金属量
            double kczjJsl = 0;
            //重算增减（±）金属量
            double cszjJsl = 0;
            //年末保有 金属量
            double nmbyJsl = 0;
            //累计查明 金属量
            double ljcmJsl = 0;
            //审批压覆量 金属量
            double spyflJsl = 0;
            //其他 金属量
            double otherDataJsl = 0;


            //年初保有矿石量
            double ncbyKsl = 0.0;
            //年初累计矿石量
            double ncljKsl = 0.0;
            //开采量 矿石量
            double kclKsl = 0;
            //损失量 矿石量
            double sslKsl = 0;
            //勘察增减（±） 矿石量
            double kczjKsl = 0;
            //重算增减（±）矿石量
            double cszjKsl = 0;
            //年末保有 矿石量
            double nmbyKsl = 0;
            //累计查明 矿石量
            double ljcmKsl = 0;
            //审批压覆量 矿石量
            double spyflKsl = 0;
            //其他 矿石量
            double otherDataKsl = 0;
            for (KsZyclhz ksZyclhz : ksZyclhzList) {

                //年末保有
                nmbyJsl += ksZyclhz.getNmbyjsl();
                nmbyKsl += ksZyclhz.getNmbyksl();

                //累计查明
                ljcmKsl += ksZyclhz.getLjcmksl();
                ljcmJsl += ksZyclhz.getLjcmjsl();

                //开采量
                kclJsl += ksZyclhz.getKcljsl();
                kclKsl += ksZyclhz.getKclksl();

                //损失量
                sslJsl += ksZyclhz.getSsljsl();
                sslKsl += ksZyclhz.getSslksl();

                //勘察增减
                kczjJsl += ksZyclhz.getKczjjsl();
                kczjKsl += ksZyclhz.getKczjksl();

                //重算增减
                cszjJsl += ksZyclhz.getCszjjsl();
                cszjKsl += ksZyclhz.getCszjksl();

                //审批压覆量
                spyflJsl += ksZyclhz.getSpyfjsl();
                spyflKsl += ksZyclhz.getSpyfksl();

                //其他
                otherDataJsl += ksZyclhz.getOtherdatajsl();
                otherDataKsl += ksZyclhz.getOtherdataksl();

                //年初保有
                ncbyJsl += ksZyclhz.getNcbyjsl();
                ncbyKsl += ksZyclhz.getNcbyksl();


                //年初累计
                ncljJsl += ksZyclhz.getNcljjsl();
                ncljKsl += ksZyclhz.getNcljksl();

            }

            ksxxhzVo.setNmbyjsl(ToolData.roundToTwoDecimals(nmbyJsl));
            ksxxhzVo.setNmbyksl(ToolData.roundToTwoDecimals(nmbyKsl));

            ksxxhzVo.setKcljsl(ToolData.roundToTwoDecimals(kclJsl));
            ksxxhzVo.setKclksl(ToolData.roundToTwoDecimals(kclKsl));

            ksxxhzVo.setSsljsl(ToolData.roundToTwoDecimals(sslJsl));
            ksxxhzVo.setSslksl(ToolData.roundToTwoDecimals(sslKsl));

            ksxxhzVo.setKczjjsl(ToolData.roundToTwoDecimals(kczjJsl));
            ksxxhzVo.setKczjksl(ToolData.roundToTwoDecimals(kczjKsl));

            ksxxhzVo.setCszjjsl(ToolData.roundToTwoDecimals(cszjJsl));
            ksxxhzVo.setCszjksl(ToolData.roundToTwoDecimals(cszjKsl));

            ksxxhzVo.setSpyfjsl(ToolData.roundToTwoDecimals(spyflJsl));
            ksxxhzVo.setSpyfksl(ToolData.roundToTwoDecimals(spyflKsl));

            ksxxhzVo.setOtherdatajsl(ToolData.roundToTwoDecimals(otherDataJsl));
            ksxxhzVo.setOtherdataksl(ToolData.roundToTwoDecimals(otherDataKsl));

            ksxxhzVo.setLjcmjsl(ToolData.roundToTwoDecimals(ljcmJsl));
            ksxxhzVo.setLjcmksl(ToolData.roundToTwoDecimals(ljcmKsl));

            ksxxhzVo.setNcljjsl(ToolData.roundToTwoDecimals(ncljJsl));
            ksxxhzVo.setNcljksl(ToolData.roundToTwoDecimals(ncljKsl));

            ksxxhzVo.setNcbyjsl(ToolData.roundToTwoDecimals(ncbyJsl));
            ksxxhzVo.setNcbyksl(ToolData.roundToTwoDecimals(ncbyKsl));

            if (zycl.getJsldw() != null) {
                ksxxhzVo.setJsldw(zycl.getJsldw());
            }

            ksxxhzVo.setKsldw(zycl.getKsldw());


        }
    }

    /**
     * 资源储量总计计算
     */

    public KsxxcxhjVo getZyzlzj(List<KsQueryCriteria> ksList) {
        KsxxcxhjVo ksxxcxhjVo = new KsxxcxhjVo();
        ksxxcxhjVo.setZj(ksList.size());
        LambdaQueryWrapper<KsZyclhz> ksZyclhzQueryWrapper = new LambdaQueryWrapper<>();
        ksZyclhzQueryWrapper.in(KsZyclhz::getZycllx, "TM", "TD", "KZ");
        ksZyclhzQueryWrapper.eq(KsZyclhz::getNd, ksList.get(0).getNd());
        ksZyclhzQueryWrapper.eq(KsZyclhz::getKcdm, ksList.get(0).getKcdm());
        ksZyclhzQueryWrapper.eq(KsZyclhz::getTjdx, ksList.get(0).getTjdx());
        List<String> kqbhList = ksList.stream().map(KsQueryCriteria::getKqbh).collect(Collectors.toList());
        ksZyclhzQueryWrapper.in(KsZyclhz::getKqbh, kqbhList);
        List<KsZyclhz> ksZyclhzList = ksZyclhzMapper.selectList(ksZyclhzQueryWrapper);

        if (ksZyclhzList != null) {
            //年初保有金属量
            double ncbyJsl = 0.0;
            //年初累计金属量
            double ncljJsl = 0.0;
            //开采量 金属量
            double kclJsl = 0;
            //损失量 金属量
            double sslJsl = 0;
            //勘察增减（±） 金属量
            double kczjJsl = 0;
            //重算增减（±）金属量
            double cszjJsl = 0;
            //年末保有 金属量
            double nmbyJsl = 0;
            //累计查明 金属量
            double ljcmJsl = 0;
            //审批压覆量 金属量
            double spyflJsl = 0;
            //其他 金属量
            double otherDataJsl = 0;


            //年初保有矿石量
            double ncbyKsl = 0.0;
            //年初累计矿石量
            double ncljKsl = 0.0;
            //开采量 矿石量
            double kclKsl = 0;
            //损失量 矿石量
            double sslKsl = 0;
            //勘察增减（±） 矿石量
            double kczjKsl = 0;
            //重算增减（±）矿石量
            double cszjKsl = 0;
            //年末保有 矿石量
            double nmbyKsl = 0;
            //累计查明 矿石量
            double ljcmKsl = 0;
            //审批压覆量 矿石量
            double spyflKsl = 0;
            //其他 矿石量
            double otherDataKsl = 0;
            for (KsZyclhz ksZyclhz : ksZyclhzList) {

                //年末保有
                nmbyJsl += ksZyclhz.getNmbyjsl();
                nmbyKsl += ksZyclhz.getNmbyksl();

                //累计查明
                ljcmKsl += ksZyclhz.getLjcmksl();
                ljcmJsl += ksZyclhz.getLjcmjsl();

                //开采量
                kclJsl += ksZyclhz.getKcljsl();
                kclKsl += ksZyclhz.getKclksl();

                //损失量
                sslJsl += ksZyclhz.getSsljsl();
                sslKsl += ksZyclhz.getSslksl();

                //勘察增减
                kczjJsl += ksZyclhz.getKczjjsl();
                kczjKsl += ksZyclhz.getKczjksl();

                //重算增减
                cszjJsl += ksZyclhz.getCszjjsl();
                cszjKsl += ksZyclhz.getCszjksl();

                //审批压覆量
                spyflJsl += ksZyclhz.getSpyfjsl();
                spyflKsl += ksZyclhz.getSpyfksl();

                //其他
                otherDataJsl += ksZyclhz.getOtherdatajsl();
                otherDataKsl += ksZyclhz.getOtherdataksl();

                //年初保有
                ncbyJsl += ksZyclhz.getNcbyjsl();
                ncbyKsl += ksZyclhz.getNcbyksl();


                //年初累计
                ncljJsl += ksZyclhz.getNcljjsl();
                ncljKsl += ksZyclhz.getNcljksl();

            }

            ksxxcxhjVo.setNmbyjsl(ToolData.roundToTwoDecimals(nmbyJsl));
            ksxxcxhjVo.setNmbyksl(ToolData.roundToTwoDecimals(nmbyKsl));

            ksxxcxhjVo.setKcljsl(ToolData.roundToTwoDecimals(kclJsl));
            ksxxcxhjVo.setKclksl(ToolData.roundToTwoDecimals(kclKsl));

            ksxxcxhjVo.setSsljsl(ToolData.roundToTwoDecimals(sslJsl));
            ksxxcxhjVo.setSslksl(ToolData.roundToTwoDecimals(sslKsl));

            ksxxcxhjVo.setKczjjsl(ToolData.roundToTwoDecimals(kczjJsl));
            ksxxcxhjVo.setKczjksl(ToolData.roundToTwoDecimals(kczjKsl));

            ksxxcxhjVo.setCszjjsl(ToolData.roundToTwoDecimals(cszjJsl));
            ksxxcxhjVo.setCszjksl(ToolData.roundToTwoDecimals(cszjKsl));

            ksxxcxhjVo.setSpyfjsl(ToolData.roundToTwoDecimals(spyflJsl));
            ksxxcxhjVo.setSpyfksl(ToolData.roundToTwoDecimals(spyflKsl));

            ksxxcxhjVo.setOtherdatajsl(ToolData.roundToTwoDecimals(otherDataJsl));
            ksxxcxhjVo.setOtherdataksl(ToolData.roundToTwoDecimals(otherDataKsl));

            ksxxcxhjVo.setLjcmjsl(ToolData.roundToTwoDecimals(ljcmJsl));
            ksxxcxhjVo.setLjcmksl(ToolData.roundToTwoDecimals(ljcmKsl));

            ksxxcxhjVo.setNcljjsl(ToolData.roundToTwoDecimals(ncljJsl));
            ksxxcxhjVo.setNcljksl(ToolData.roundToTwoDecimals(ncljKsl));

            ksxxcxhjVo.setNcbyjsl(ToolData.roundToTwoDecimals(ncbyJsl));
            ksxxcxhjVo.setNcbyksl(ToolData.roundToTwoDecimals(ncbyKsl));

        }
        return ksxxcxhjVo;

    }


    /**
     * 查询统计通用sql
     */

    public String getSql(CxtjMhtj cxtjMhtj) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());
        String sql = "where";
//拼接年度信息
        if (cxtjMhtj.getNd() != null) {
            sql += " nd=" + cxtjMhtj.getNd() + " and";
        }
//拼接矿山名称信息
        if (cxtjMhtj.getKsmc() != null) {
            sql += " ksmc like '%" + cxtjMhtj.getKsmc() + "%' and";
        }

//拼接矿区编号信息
        if (cxtjMhtj.getKqbh() != null) {
            sql += " kqbh like '%" + cxtjMhtj.getKqbh() + "%' and";
        }

//拼接矿区名称
        if (cxtjMhtj.getKqmc() != null) {
            sql += " kqmc like '%" + cxtjMhtj.getKqmc() + "%' and";
        }

//拼接矿种
        if (cxtjMhtj.getKzbh() != null) {
            List<Integer> kzbhList = TypeProcessing.strToList(cxtjMhtj.getKzbh());
            if (kzbhList != null && kzbhList.size() == 3) {
                if (kzbhList.get(0) == 2) {
                    sql += " kcdm=" + kzbhList.get(1) + " and";
                } else if (kzbhList.get(0) == 3) {
                    sql += " kcdm='" + kzbhList.get(1) + "' and tjdx=" + kzbhList.get(2) + " and";
                }
            }
        }

//登记分类编号
        if (cxtjMhtj.getDjflbh() != null) {
            sql += " djflbh='" + cxtjMhtj.getDjflbh() + "' and";
        }
//矿业权人
        if (cxtjMhtj.getKyqr() != null) {
            sql += " kyqr='" + cxtjMhtj.getKyqr() + "' and";
        }
//规模
        if (cxtjMhtj.getGm() != null) {
            sql += " gm='" + cxtjMhtj.getGm() + "' and";
        }
//利用情况
        if (cxtjMhtj.getSfly() != null) {
            sql += " sfly=" + cxtjMhtj.getSfly() + " and";
        }
//有效期模糊查询
        if (cxtjMhtj.getYxq() != null) {
            sql += " jzyxq like '%" + cxtjMhtj.getYxq() + "%' and";
        }
//行政区代码级联多选
        if (cxtjMhtj.getXzqh() != null) {
            List<String> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim) // 去除前后空白
                    .collect(Collectors.toList());

            String xzqsql = "(";

            for (String xzqh : xzqhList) {
                xzqsql += "'" + xzqh + "',";
            }
            xzqsql = xzqsql.substring(0, xzqsql.length() - 1) + ")";
            sql += " xzqdm in " + xzqsql + " and";
        } else {
            //行政区代码
            String xzqh = "";
            if (user.getOrgId() != null) {
                if (user.getOrgId().equals("-1")) {
                    xzqh = "130000";
                } else {
                    xzqh = user.getOrgId();
                }
            } else {
                xzqh = "130000";
            }

            xzqh = xzqh.replaceAll("0+$", "");
            sql += " xzqdm like '" + xzqh + "%' and";
        }
//许可证号
        if (cxtjMhtj.getXkzh() != null) {
            sql += " xkzh='" + cxtjMhtj.getXkzh() + "' and";
        }
//勘察程度
        if (cxtjMhtj.getKccd() != null) {
            sql += " kcjdm=" + cxtjMhtj.getKccd() + " and";
        }

//开采情况（0未开采，1开采）
        if (cxtjMhtj.getKcqk() != null) {
            sql += " kcqk=" + cxtjMhtj.getKcqk() + " and";
        }

//是否出界（0未出界，1出界）
        if (cxtjMhtj.getSfcj() != null) {
            sql += " sfcj=" + cxtjMhtj.getSfcj() + " and";
        }
//矿产组合码
        if (cxtjMhtj.getKczh() != null) {
            LambdaQueryWrapper<Cb01Zh> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Cb01Zh::getBh, 16);
            queryWrapper.eq(Cb01Zh::getBnm, Integer.valueOf(cxtjMhtj.getKczh()));
            Cb01Zh cb01Zh = cb01ZhMapper.selectOne(queryWrapper);
            if (cb01Zh != null) {
                sql += " kczhm=" + cb01Zh.getDm() + " and";
            }
        }
        // 矿业权类型（1：无矿权，2：采矿权，3：探矿权）
        if (cxtjMhtj.getKqlx() != null) {
            sql += " kqlx=" + cxtjMhtj.getKqlx() + " and";
        }

        sql = sql.substring(0, sql.length() - 4);
        return sql;
    }

    /**
     * 查询统计通用sql
     */

    public String getSqlKcd(CxtjMhtj cxtjMhtj) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());
        String sql = "where";
//拼接年度信息
        if (cxtjMhtj.getNd() != null) {
            sql += " ks.nd=" + cxtjMhtj.getNd() + " and";
        }
//拼接矿山名称信息
        if (cxtjMhtj.getKsmc() != null) {
            sql += " ks.ksmc like '%" + cxtjMhtj.getKsmc() + "%' and";
        }

//拼接矿区编号信息
        if (cxtjMhtj.getKqbh() != null) {
            sql += " ks.kqbh like '%" + cxtjMhtj.getKqbh() + "%' and";
        }

//拼接矿区名称
        if (cxtjMhtj.getKqmc() != null) {
            sql += " ks.kqmc like '%" + cxtjMhtj.getKqmc() + "%' and";
        }

//拼接矿种
        if (cxtjMhtj.getKzbh() != null) {
            if (cxtjMhtj.getKzbh().contains(",")) {
                List<Integer> kzbhList = TypeProcessing.strToListComma(cxtjMhtj.getKzbh());

                String str = "(";
                for (Integer kzbh : kzbhList) {
                    str += "'" + kzbh + "',";
                }
                str = str.substring(0, str.length() - 1) + ")";
                sql += " ks.kcdm in " + str + " and";
            } else {
                List<Integer> kzbhList = TypeProcessing.strToList(cxtjMhtj.getKzbh());
                if (kzbhList != null && kzbhList.size() == 3) {
                    sql += " ks.kcdm='" + kzbhList.get(1) + "' and ks.tjdx=" + kzbhList.get(2) + " and";
                }
            }
        }


//登记分类编号
        if (cxtjMhtj.getDjflbh() != null) {
            sql += " ks.djflbh='" + cxtjMhtj.getDjflbh() + "' and";
        }
//矿业权人
        if (cxtjMhtj.getKyqr() != null) {
            sql += " ks.kyqr='" + cxtjMhtj.getKyqr() + "' and";
        }
//规模
        if (cxtjMhtj.getGm() != null) {
            sql += " ks.gm='" + cxtjMhtj.getGm() + "' and";
        }
//利用情况
        if (cxtjMhtj.getSfly() != null) {
            sql += " ks.sfly=" + cxtjMhtj.getSfly() + " and";
        }
//有效期模糊查询
        if (cxtjMhtj.getYxq() != null) {
            sql += " ks.yxq like '%" + cxtjMhtj.getYxq() + "%' and";
        }
//行政区代码级联多选
        if (cxtjMhtj.getXzqh() != null) {
            List<String> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim) // 去除前后空白
                    .collect(Collectors.toList());

            String xzqsql = "(";

            for (String xzqh : xzqhList) {
                xzqsql += "'" + xzqh + "',";
            }
            xzqsql = xzqsql.substring(0, xzqsql.length() - 1) + ")";
            sql += " ks.xzqdm in " + xzqsql + " and";
        } else {
            //行政区代码
            String xzqh = "";
            if (user.getOrgId() != null) {
                if (user.getOrgId().equals("-1")) {
                    xzqh = "130000";
                } else {
                    xzqh = user.getOrgId();
                }
            } else {
                xzqh = "130000";
            }

            xzqh = xzqh.replaceAll("0+$", "");
            sql += " ks.xzqdm like '" + xzqh + "%' and";
        }
//许可证号
        if (cxtjMhtj.getXkzh() != null) {
            sql += " ks.xkzh='" + cxtjMhtj.getXkzh() + "' and";
        }
//勘察程度
        if (cxtjMhtj.getKccd() != null) {
            sql += " ks.kcjdm=" + cxtjMhtj.getKccd() + " and";
        }

//开采情况（0未开采，1开采）
        if (cxtjMhtj.getKcqk() != null) {
            sql += " ks.kcqk=" + cxtjMhtj.getKcqk() + " and";
        }

//是否出界（0未出界，1出界）
        if (cxtjMhtj.getSfcj() != null) {
            sql += " ks.sfcj=" + cxtjMhtj.getSfcj() + " and";
        }
//矿产组合码
        if (cxtjMhtj.getKczh() != null) {
            LambdaQueryWrapper<Cb01Zh> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Cb01Zh::getBh, 16);
            queryWrapper.eq(Cb01Zh::getBnm, Integer.valueOf(cxtjMhtj.getKczh()));
            Cb01Zh cb01Zh = cb01ZhMapper.selectOne(queryWrapper);
            if (cb01Zh != null) {
                sql += " ks.kczhm=" + cb01Zh.getDm() + " and";
            }
        }
        // 矿业权类型（1：无矿权，2：采矿权，3：探矿权）
        if (cxtjMhtj.getKqlx() != null) {
            sql += " ks.kqlx=" + cxtjMhtj.getKqlx() + " and";
        }

        sql = sql.substring(0, sql.length() - 4);
        return sql;
    }

    /**
     * 全县年度保有量折线图
     *
     * @param kcdm 矿产代码
     * @author Kevin
     * @since 2024/7/19 23:01
     */
    @Override
    public Chart<Double> lineChartXian(Integer kcdm) {
        QueryWrapper<Map> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("kcdm", kcdm);
        queryWrapper.eq("xzqdm", UserUtil.getCurrentUserXzqhdm());
        queryWrapper.ne("sbbsm", 3);
        List<ChartVo> list = kshzMapper.lineChartXian(queryWrapper);

        //X轴-年份
        List<Object> xData = new ArrayList<>();
        //Y轴-List<Map<参数, List<每年的值>>>
        List<YData<Double>> yData = new ArrayList<>();

        //年末保有量
        List<Double> dataList = new ArrayList<>();

        for (ChartVo data : list) {
            xData.add(data.getNd());
            dataList.add(data.getValue());
        }
        yData.add(new YData<>("保有量", "byl", ChartTypeConstants.line, dataList));
        return new Chart<>(xData, yData);
    }

    /**
     * 年度各类矿产地统计饼状图
     *
     * @param nd 年度
     * @author Kevin
     * @since 2024/7/19 23:01
     */
    @Override
    public List<Map> barChartXianKcd(Integer nd) {
        QueryWrapper<Map> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hz.nd", nd);
        queryWrapper.likeRight("hz.xzqdm", UserUtil.getCurrentUserXzqhdm());
        return kshzMapper.barChartXianKcd(queryWrapper);
    }

    /**
     * 年度各类矿产地统计柱状图
     *
     * @param nd 年度
     * @author Kevin
     * @since 2024/7/19 23:01
     */
    @Override
    public CommonChart lineChartXianKcd(Integer nd) {
        QueryWrapper<Map> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hz.nd", nd);
        queryWrapper.ne("hz.sbbsm", 3);
        queryWrapper.likeRight("hz.xzqdm", UserUtil.getCurrentUserXzqhdm());
        List<Map> list = kshzMapper.barChartXianKcd(queryWrapper);

        //X轴-名称
        List<Object> xData = new ArrayList<>();
        //Y轴-List<Map<参数, List<每个名称对应的值>>>
        List<CommonYData> yData = new ArrayList<>();

        //矿产地
        List<Object> dataList = new ArrayList<>();

        for (Map map : list) {
            xData.add(map.get("name"));
            dataList.add(map.get("value"));
        }
        yData.add(new CommonYData("矿产地", "kcd", ChartTypeConstants.bar, dataList));
        return new CommonChart(xData, yData);
    }

    /**
     * 年度矿产地勘查程度统计饼状图
     *
     * @param nd 年度
     * @author Kevin
     * @since 2024/7/19 23:01
     */
    @Override
    public List<Map> barChartXianKccd(Integer nd) {
        QueryWrapper<Map> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c.bh", 15);
        queryWrapper.ne("c.bnm", 0);
        queryWrapper.eq("hz.nd", nd);
        queryWrapper.likeRight("hz.xzqdm", UserUtil.getCurrentUserXzqhdm());
        return kshzMapper.barChartXianKccd(queryWrapper);
    }

    /**
     * 年度矿产地规模统计饼状图
     *
     * @param nd 年度
     * @author Kevin
     * @since 2024/7/19 23:01
     */
    @Override
    public List<Map> barChartXianGm(Integer nd) {
        QueryWrapper<Map> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("hz.gm");
        queryWrapper.eq("hz.nd", nd);
        queryWrapper.likeRight("hz.xzqdm", UserUtil.getCurrentUserXzqhdm());
        return kshzMapper.barChartXianGm(queryWrapper);
    }

    @Override
    public void getCxtjsljs() {
        List<Kshz> list = new ArrayList<>();
        LambdaQueryWrapper<Kshz> queryWrapper = new LambdaQueryWrapper<>();
        list = kshzMapper.selectList(queryWrapper);
        for (Kshz kshz : list) {
            try {
                LambdaQueryWrapper<Ks> ksqueryWrapper = new LambdaQueryWrapper<>();
                ksqueryWrapper.eq(Ks::getNd, kshz.getNd());
                ksqueryWrapper.eq(Ks::getKqbh, kshz.getKqbh());
                ksqueryWrapper.eq(Ks::getDjflbh, 1000);
                Ks ks = ksMapper.selectOne(ksqueryWrapper);
                kshz.setKqmc(ks.getKsmc());
                kshzMapper.updateById(kshz);
            } catch (Exception e) {
                System.out.println(kshz.getKqbh() + "---数据更新失败");
            }

        }
    }

    @Override
    public Page<KsxxhzVo> includeHisKshzPage(CxtjMhtj cxtjMhtj) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());
        List<String> ksxxhzList = kslsjuMapper.getKsxxhzList();
        // 构建IN子句
        StringBuilder inClause = new StringBuilder();
        for (int i = 0; i < ksxxhzList.size(); i++) {
            if (i > 0) {
                inClause.append(", ");
            }
            inClause.append("'").append(ksxxhzList.get(i)).append("'");
        }

        Page<Kshz> page = new Page<>();
        Page<KsxxhzVo> returnPage = new Page<>();

        page.setCurrent(cxtjMhtj.getCurrent());
        page.setSize(cxtjMhtj.getSize());
        QueryWrapper<Kshz> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("(kqbh || '_' || djflbh)", inClause.toString());


        // 拼接年度信息
        if (cxtjMhtj.getNd() != null) {
            queryWrapper.eq("nd", cxtjMhtj.getNd());
        }
// 拼接矿种
        if (cxtjMhtj.getKzbh() != null) {
            if (cxtjMhtj.getKzbh().contains(",") || !cxtjMhtj.getKzbh().contains("_")) {
                List<Integer> kzbhList = TypeProcessing.strToListComma(cxtjMhtj.getKzbh());
                queryWrapper.in("kcdm", kzbhList);
            }
        }

// 上表标识 支持多选（1,2,3）
        if (cxtjMhtj.getSbbs() != null) {
            List<Integer> sbbsList = Arrays.stream(cxtjMhtj.getSbbs().split(","))
                    .map(String::trim)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            queryWrapper.in("sbbsm", sbbsList);
        }
// 行政区代码级联多选
        String xzqh = user.getOrgId() != null ? user.getOrgId() : "130000";
        xzqh = xzqh.replaceAll("0+$", "");
        queryWrapper.like("xzqdm", xzqh);
// 矿业权类型（1：无矿权，2：采矿权，3：探矿权）
        if (cxtjMhtj.getKqlx() != null) {
            queryWrapper.eq("kqlx", cxtjMhtj.getKqlx());
        }

// 排序
        queryWrapper.orderByDesc("nd");
        queryWrapper.orderByAsc("kqbh");

        page = kshzMapper.selectPage(page, queryWrapper);
        List<Kshz> kshzList = page.getRecords();

        List<KsxxhzVo> ksxxhzVoList = new ArrayList<>();

        for (Kshz kshz : kshzList) {
            KsxxhzVo ksxxhzVo = new KsxxhzVo();
            BeanUtil.copyProperties(kshz, ksxxhzVo);

            String xzqhmc = cb08XzqhMapper.getXzqhmc(Integer.parseInt(kshz.getXzqdm()));
            ksxxhzVo.setXzqhmc(xzqhmc);

            QueryWrapper<Cb06Kc> queryWrapperKc = new QueryWrapper<>();
            queryWrapperKc.eq("kcdm", ksxxhzVo.getKcdm());
            queryWrapperKc.last("limit 1");
            Cb06Kc cb06Kc = cb06KcMapper.selectOne(queryWrapperKc);
            ksxxhzVo.setKcmc(cb06Kc.getKcmc());
            ksxxhzVo.setJsdxmc(cb06Kc.getJsdxmc());
            ksxxhzVoList.add(ksxxhzVo);
        }

        returnPage.setSize(page.getSize());
        returnPage.setCurrent(page.getCurrent());
        returnPage.setTotal(page.getTotal());
        returnPage.setRecords(ksxxhzVoList);
        return returnPage;
    }


    /**
     * 下载查询条件模版
     *
     * @param response
     * @author sqq
     * @since 2025/3/31 9:54
     */
    @Override
    public void downloadQueryTemplate(HttpServletResponse response) {
        // 年报附表4模板路径
        String templateFilePath = PathUtils.getNbfbPath(14);

        // 加载模板文件
        ClassPathResource classPathResource = new ClassPathResource(templateFilePath);

        try (InputStream inputStream = classPathResource.getStream();
             OutputStream outputStream = response.getOutputStream()) {

            // 将输入流中的数据写入到输出流中
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();

        } catch (IOException e) {
            // 记录详细的错误日志
            throw new RuntimeException("下载查询条件模板失败", e);
        }

    }
}
